﻿using System;
using System.Web.Mvc;
using Direct.Core;

namespace Direct.Server.Mvc
{
    public class PrimitiveValueBinder : DefaultModelBinder
    {
        public override object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
        {
            var vp = bindingContext.ValueProvider[bindingContext.ModelName];
            var modelType = bindingContext.ModelType;

            if (vp == null)
            {
                if (TypeHelper.IsNullableValueType(modelType))
                    return null;
                else
                    bindingContext.ModelState.AddModelError(bindingContext.ModelName, "Valor requerido para a ação");
            }

            var strValue = vp.AttemptedValue;

            bindingContext.ModelState.SetModelValue(bindingContext.ModelName, bindingContext.ValueProvider[bindingContext.ModelName]);

            try
            {
                if (modelType == typeof(Boolean) || (modelType == typeof(Boolean?)))
                {
                    return strValue.EqualsIgnoreCase("on")
                        || strValue.EqualsIgnoreCase("true")
                        || strValue.EqualsIgnoreCase("1")
                        || strValue.EqualsIgnoreCase("yes")
                        || strValue.EqualsIgnoreCase("sim");
                }
                else
                    return ConversionHelper.Coerce(strValue, modelType);
            }
            catch (Exception)
            {

                bindingContext.ModelState.AddModelError(bindingContext.ModelName, String.Format("\"{0}\" é inválido", bindingContext.ModelName));
                return null;
            }
        }
    }
}
